
//规则条件列表js代码块
var SysRoleListPage = {
		
		//初始化一些东西
		init : function(){
			
		},
		
		//初始化菜单树
		initMenuTree : function(){
			
			var requestUrl ="/menu/getRoleBindSysMenu";
			
			 ajaxRequestAsync(requestUrl , {"roleId" : this.currentUpdateRecord.id + ""} , function(rst){
				 
				 var data = rst.data;
				 
				 if(!data || data.length == null) return;
				 
				 var menuTxt = SysRoleListPage.createMenuTxt(data);
				 
				 $("#menuLayerId").html(menuTxt).find("ul").show();
				 
			 });
		},
		
		//创建菜单
		createMenuTxt : function(dataList){
			
			var txt = '';
			
			var isRootNode = false;
			
			for(var i = 0 ; i < dataList.length ; i ++){
				
				var item = dataList[i];
				
				//根基诶单
				isRootNode = !item.parentMenuId || item.parentMenuId == null;
				
				var params = {"bindFlag" : item.bindFlag , "name": item.name , "url" : item.url , "icon" : item.icon ,  "menuNo":item.menuNo , "type": item.type , "id": item.id+"" , "parentId" : isRootNode ? undefined : item.parentMenuId + "" };
				
				var itemTxt = this.createNode(params);
				
				var children = item.children;
				
				if(children && children.length > 0){
					
					var childrenTxt = '<ul>' + this.createMenuTxt(children) + '</ul></li>';
					
					itemTxt = itemTxt.replace("</li>" , "") + childrenTxt;
					
				}
				
				txt += itemTxt;
			}
			
			return txt;
			
		},
		
		//创建节点
		createNode : function(params) {
			
			var name = params.name;
			var id = params.id + "";
			var icon = params.icon;
			var url = params.url;
			var parentId = params.parentId;
			var type = params.type;
			var menuNo = params.menuNo;
			var bindFlag = params.bindFlag;
			
			//转化为字符串 , 不然传入到参数中又会变为长整型而失去精度
			id = id + "";
			
			icon = !icon || icon == "" ? "icon-file-o" : icon;
			
			var nameTxt = name && name != "" ? ' name="'+name+'" ' : ""; 
			var iconTxt = ' icon="'+icon+'" ';
			var urlTxt = url && url != ""  ? ' url="'+url+'" ' : ""; 
			var idTxt = id && id != "" ? ' id="'+id+'" ' : ""; 
			var parentIdTxt = parentId && parentId != "" ? ' parentId="'+parentId+'" ' : ""; 
			var typeTxt = type && type != "" ? ' type="'+type+'" ' : ""; 
			var menuNoTxt = menuNo && menuNo != "" ? ' menuNo="'+menuNo+'" ' : ""; 
			var menuInfoTxt = idTxt + nameTxt + iconTxt + urlTxt + typeTxt + menuNoTxt + parentIdTxt;
			var checkedTxt = bindFlag ? ' checked="checked" ' : "";
			
			var txt = '';
			
			if(type == 0){
				txt = '<li '+menuInfoTxt+' ><input type="checkbox" '+checkedTxt+' class="menuCheckbox" id="'+id+'"  style="cursor:pointer;" onclick="SysRoleListPage.clickMenuCheckbox(this);"/>&nbsp;<a href="javascript:void(0);"><i class="icon '+icon+'"></i>&nbsp;<span>'+name+'</span></a>&nbsp;';
			}else{
				txt = '<li '+menuInfoTxt+' ><input type="checkbox" '+checkedTxt+' class="menuCheckbox" id="'+id+'" style="cursor:pointer;" onclick="SysRoleListPage.clickMenuCheckbox(this);" />&nbsp;<a href="javascript:void(0);"><button style="font-size:12px;" type="button" disabled="disabled">按钮</button>&nbsp;<span>'+name+'</span></a>&nbsp;';
			}
		
			return 	txt;
		},
		
		//勾选菜单
		clickMenuCheckbox : function(tag){
			
			//是否被勾选
			var flag = $(tag).is(":checked");
			
			//若是被勾选 , 父亲节点下的都得被勾选
			if(flag){
				$(tag).parents("li").children("input").attr("checked" , "checked");
			}else{
				$(tag).parent("li").find("li").children("input").removeAttr("checked");
			}
			
		},
		
		 /*创建分页实例current*/
	    pagingTooler : new PagingTooler({
	        callbackMethodName : "SysRoleListPage.findSysRoleList",
	        pageSize : 10,
	        firstPageBtnID : "firstPageBtn",
	        lastPageBtnID : "lastPageBtn",
	        pageCodeLayerID : "pageCodeLayer",
	        recordListLayerID : "dataListLayer",
	        showCurrentPageLayerID : "currentPageLayer",
	        showRecordCountLayerID : "recordCountLayer",
	        showPageCountLayerID : "pageCountLayer",
	        showLoadingLayerID : "loadingLayer",
	        showNoRecordLayerID : "recordLayer",
	        pagingToolbarLayerID : "pagingToolbarLayer",
	        pageSizeSelectLayerID : "pageSizeSelectLayer",
	        jumpPageCodeInputID : "pageInput",
	        jumpPageBtnID : "goPageBtn",
	        pageSizeArray : [10,15,20],
	        hideColumnLayerID : "hideColumnLayer",   //隐藏列div的ID
	    }),
	    
	    search : function(){
	    	var forms = $(".searchParameter");
			var params = {};
			for(var i = 0 ; i < forms.length; i ++){
				var form = $(forms[i]);
				var id = form.attr("id");
				id = id.replace("search_","");
				var value = $.trim(form.val());
				if(value == "") continue;
				params[id] = value;
			}
			
			this.pagingTooler.search(params);
			
	    },
	    
	    findSysRoleList : function(){
	    	
	    	var params = this.pagingTooler.getPagingAndSearchParams();
	    	
	     	$.ajax({
			 	url : '/sysRole/findSysRoleList',
			 	type :'POST',
			 	data : JSON.stringify(params),
			 	dataType : "json",
			 	contentType : 'application/json; charset=UTF-8',
			 	success:function(data){
			 		var count = data.data.total;
			 		var dataList = data.data.list;
			 		var txt = "";
			 		SysRoleListPage.dataList = dataList;
			 		for(var i = 0 ; dataList != null && i < dataList.length ; i ++){
			 			txt +=SysRoleListPage.createRecordTxt(dataList[i], i)
			 		}
			 		SysRoleListPage.pagingTooler.showInPage(count, txt,"currentNumberPage");
			 	}		
			 });

	    },
	    
	    //创建表格中每一条记录的文本
	    createRecordTxt : function(data , index){
	    	
	    	var txt = "";
	    	  
			txt = '<tr>'+
						'<td><input type="checkbox" class="checkitem"/></td>'+
						'<td>'+CommonUtil.fillBlank(data.roleName)+'</td>'+
						'<td>'+CommonUtil.fillBlank(data.roleNo)+'</td>'+
						'<td>'+CommonUtil.fillBlank(data.remark)+'</td>'+
	    				'<td>'+
		    				'<button onclick="SysRoleListPage.popDetailSysRoleWindow('+index+')"  class="btn btn-mini">查看</button>&nbsp;'+
		    				'<button onclick="SysRoleListPage.popPermissionWindow('+index+')"  class="btn btn-mini permissionMenu roleBindMenuOpenWindowBtn">权限</button>&nbsp;'+
		    				'<button onclick="SysRoleListPage.popEditSysRoleWindow('+index+')"  class="btn btn-mini  permissionMenu editRoleBtn">编辑</button>&nbsp;'+
		    				'<button onclick="SysRoleListPage.popBindUserWindow('+index+')"  class="btn btn-mini  permissionMenu roleBindUserOpenWindowBtn">绑定用户</button>&nbsp;'+
	    					'<button onclick="SysRoleListPage.popDeleteSysRoleWindow('+index+')"  class="btn btn-mini  permissionMenu deleteRoleBtn">删除</button>&nbsp;'+
    					'</td>'+
	    			  '</tr>';
	    	return txt;
	    },
	    
	    //弹出绑定用户弹窗
	    popBindUserWindow : function(index){
	    	
	     	//当前编辑对象
	    	this.currentUpdateRecord = this.dataList[index];
	    	
	    	var currentUpdateRecord = this.currentUpdateRecord;
	    	
	    	//加载用户
	    	this.findUserList();
	    	
	    	$("#currentBindRoleSpan").html("【"+currentUpdateRecord.roleName+"】");
	    	$("#bindUserWindow").modal();
	    	
	    },
	    
	    //弹出权限设置弹窗
	    popPermissionWindow : function(index){
	    	
	     	//当前编辑对象
	    	this.currentUpdateRecord = this.dataList[index];
	    	
	    	var currentUpdateRecord = this.currentUpdateRecord;
	    	
	    	//初始化树形菜单
	    	this.initMenuTree();
	    	
	    	$("#permissionWindow").modal();
	    	
	    },
	    
	    //确认权限设置
	    surePermission : function(){
	    	
	    	var checkArr  = $(".menuCheckbox:checked");
	    	
	    	var menuIds = [];
	    	
	    	for(var i  = 0 ; i < checkArr.length ; i ++){
	    		menuIds.push($(checkArr[i]).attr("id") + "");
	    	}
	    	
	    	var params = {"id" : this.currentUpdateRecord.id + "" , "menuIds" : menuIds};
	    	
			var requestUrl ="/sysRole/roleBindMenus";
			
			ajaxRequestByJSONParams(requestUrl , params , function(rst){
				 
				 var tipType = rst.code == 200 ? "success" : "danger";
				 
				 new $.zui.Messager(rst.message, {icon:'times' ,type: tipType ,placement: 'center',time:'2000'}).show();
				 
				 if(rst.code == 200){
					 $("#permissionWindow").modal("hide");
				 }
				 
			 });
	    	
	    },
	    
	    //弹出编辑窗口
	    popEditSysRoleWindow : function(index){
	     	
	     	//当前编辑对象
	    	this.currentUpdateRecord = this.dataList[index];
	    	
	    	var currentUpdateRecord = this.currentUpdateRecord;
	    	
	    	//显示弹窗
	     	$('#editSysRoleWindow').attr("editId" , currentUpdateRecord.id).modal();
	     	
	     	for(var key in currentUpdateRecord){
	     		
	     		var value = currentUpdateRecord[key];
	     		
	     		if(key == "birthday" && value && value != "" && value != null){
	     			$("#edit_" + key).val(CommonUtil.getDateYmd(new Date(value)));
	     		}else{
	     			$("#edit_" + key).val(value);
	     		}
	     		
	     	}
	     	
	    },
	    
	  //获取编辑窗口的表单参数
      getUpdateSysRoleFormParams : function(){
	    	
	    	var params = {};
	    	
			params.roleName =  $.trim($("#edit_roleName").val());
			params.roleNo =  $.trim($("#edit_roleNo").val());
			params.remark =  $.trim($("#edit_remark").val());
			
			params.id = this.currentUpdateRecord.id;
			
	    	return params;
	    	
	    },
	    
	    //校验新增的参数
	    validateUpdateSysRoleFormParams : function(params){
	    	
	    	if(params.roleName == ""){
	    		new $.zui.Messager('角色名称不能为空', {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
	    		return;
	    	}
	    	
	    	if(params.roleNo == ""){
	    		new $.zui.Messager('角色编号不能为空', {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
	    		return;
	    	}
	    	
	    	//校验的逻辑自己填写,返回true和false,可以弹出一些提示
	    	return true;

	    },
	    
	    //更新
	    updateSysRole : function(){
	    	
	    	var params = this.getUpdateSysRoleFormParams();
	    	
	    	//校验不通过,直接返回
	    	if(!this.validateUpdateSysRoleFormParams(params)) return;
	    	
	    	$.ajax({
			 	url : '/sysRole/updateSysRole',
			 	type :'POST',
			 	data : JSON.stringify(params),
			 	
			 	beforeSend : function(){
			 		$("#addSysRoleBtn").attr("disabled","disabled");
			 	},
			 	complete: function(){
			 		$("#addSysRoleBtn").removeAttr("disabled","disabled");
			 	},
			 	dataType : "json",
			 	contentType : 'application/json; charset=UTF-8',
			 	success:function(data){
			 		
			 		if(data.code == 200){
			 			new $.zui.Messager('修改成功!', {icon:'check' ,type: 'success',placement: 'center',time:'2000'}).show();
			 			SysRoleListPage.findSysRoleList();
			 			$(".closeWindowBtn").click();
			 			return;
			 		}
			 		
			 		new $.zui.Messager(data.message, {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
			 		
			 	}		
			 });
	    	
	    },
	    
	  //创建菜单编号
		createRoleNo : function(type){
			
			if(type == 1){
				$("#add_roleNo").val("R" +CommonUtil.createDateNo());
			}else{
				$("#edit_roleNo").val("R" +CommonUtil.createDateNo());
			}
			
		},
	    
	    //弹出新增窗口
	    popAddSysRoleWindow : function(){
	    	
	    	$("#addSysRoleWindow").find("input").val("");
	    	
	    	//自动创建编号
	    	this.createRoleNo();
	    	
	    	//时间空间默认为当前时间
	     	$('#addSysRoleWindow').find(".form-datetime").val(CommonUtil.getCurrentTimeYmdhms());
	     	
	     	//显示弹窗
	     	$('#addSysRoleWindow').modal();
	     	
	    },
	    
	    //获取新增的表单参数
	    getAddSysRoleFormParams : function(){
	    	
	    	var params = {};
	    	
			params.roleName =  $.trim($("#add_roleName").val());
			params.roleNo =  $.trim($("#add_roleNo").val());
			params.remark =  $.trim($("#add_remark").val());
	    	
	    	return params;
	    	
	    },
	    
	    //校验新增的参数
	    validateAddSysRoleFormParams : function(params){
	    	
	    	if(params.roleName == ""){
	    		new $.zui.Messager('角色名称不能为空', {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
	    		return;
	    	}
	    	
	    	if(params.roleNo == ""){
	    		new $.zui.Messager('角色编号不能为空', {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
	    		return;
	    	}
	    	
	    	//校验的逻辑自己填写,返回true和false,可以弹出一些提示
	    	return true;

	    },
	    
	    //新增
	    addSysRole : function(){
	    	
	    	var params = this.getAddSysRoleFormParams();
	    	
	    	//校验不通过,直接返回
	    	if(!this.validateAddSysRoleFormParams(params)) return;
	    	
	    	$.ajax({
			 	url : '/sysRole/addSysRole',
			 	type :'POST',
			 	data : JSON.stringify(params),
			 	
			 	beforeSend : function(){
			 		$("#addSysRoleBtn").attr("disabled","disabled");
			 	},
			 	complete: function(){
			 		$("#addSysRoleBtn").removeAttr("disabled","disabled");
			 	},
			 	dataType : "json",
			 	contentType : 'application/json; charset=UTF-8',
			 	success:function(data){
			 		
			 		if(data.code == 200){
			 			new $.zui.Messager('新增成功!', {icon:'check' ,type: 'success',placement: 'center',time:'2000'}).show();
			 			SysRoleListPage.findSysRoleList();
			 			$(".closeWindowBtn").click();
			 			return;
			 		}
			 		
			 		new $.zui.Messager(data.message, {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
			 		
			 	}		
			 });
	    	
	    },
	    
	    //弹出详情窗口
	    popDetailSysRoleWindow : function(index){
	    	
	    	//当前编辑对象
	    	this.currentDetailRecord = this.dataList[index];
	    	
	    	var currentDetailRecord = this.currentDetailRecord;
	    	
	    	for(var key in currentDetailRecord){
	    		
	    		var value = currentDetailRecord[key];
	    		
	    		if(key.lastIndexOf("Time") != -1){
	    			value = CommonUtil.getDateYmdhms(new Date(value));
	    		}
	    		
	    		$("#detail_" + key).val(value);
	    	}
	    	
	    	$('#detailSysRoleWindow').modal();
	    },
	    
	    //弹出删除窗口
	    popDeleteSysRoleWindow : function(index){
	     	
	    	//当前删除对象
	    	this.currentDeleteRecord = this.dataList[index];
	    	
	    	$('#deleteSysRoleWindow').modal();
	    },
	    
	    //删除
	    deleteSysRole : function(){
	    	
	    	var params = {id : this.currentDeleteRecord.id};
	    	
	    	$.ajax({
			 	url : '/sysRole/deleteSysRoleById',
			 	type :'POST',
			 	data : params,
			 	beforeSend : function(){
			 		$("#deleteSysRoleBtn").attr("disabled","disabled");
			 	},
			 	complete: function(){
			 		$(".closeWindowBtn").click();
			 		$("#deleteSysRoleBtn").removeAttr("disabled","disabled");
			 	},
			 	dataType : "json",
			 	contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
			 	success:function(data){
			 		
			 		if(data.code == 200){
			 			new $.zui.Messager('删除成功!', {icon:'check' ,type: 'success',placement: 'center',time:'2000'}).show();
			 			//删除或更新后停留在当前页
			 			SysRoleListPage.pagingTooler.freshPageByDelete();
			 			return;
			 		}
			 		
			 		new $.zui.Messager(''+data.message, {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
			 		
			 	}		
			 });
	    	
	    },
	    
		 /*创建分页实例current*/
	    pagingToolerUser : new PagingTooler({
	        callbackMethodName : "SysRoleListPage.findUserList",
	        pageSize : 10,
	        firstPageBtnID : "firstPageBtn_user",
	        lastPageBtnID : "lastPageBtn_user",
	        pageCodeLayerID : "pageCodeLayer_user",
	        recordListLayerID : "dataListLayer_user",
	        showCurrentPageLayerID : "currentPageLayer_user",
	        showRecordCountLayerID : "recordCountLayer_user",
	        showPageCountLayerID : "pageCountLayer_user",
	        showLoadingLayerID : "loadingLayer_user",
	        showNoRecordLayerID : "recordLayer_user",
	        pagingToolbarLayerID : "pagingToolbarLayer_user",
	        pageSizeSelectLayerID : "pageSizeSelectLayer_user",
	        jumpPageCodeInputID : "pageInput_user",
	        jumpPageBtnID : "goPageBtn_user",
	        pageSizeArray : [10,15,20],
	        hideColumnLayerID : "hideColumnLayer_user",   //隐藏列div的ID
	    }),
	    
	    searchUser : function(){
	    	
			var params = {};
			
			params.keywords = $.trim($("#search_userKeyWords").val());
			params.bindFlag = $("#bindFlagSelect").val();
			
			this.pagingToolerUser.search(params);
			
	    },
	    
	    findUserList : function(){
	    	
	    	var params = this.pagingToolerUser.getPagingAndSearchParams();
	    	
	    	//角色id
	    	params.sysRoleId = this.currentUpdateRecord.id + "";
	    	
	     	$.ajax({
			 	url : '/sysUser/findSysUserBindRoleInfoList',
			 	type :'POST',
			 	data : JSON.stringify(params),
			 	dataType : "json",
			 	contentType : 'application/json; charset=UTF-8',
			 	success:function(data){
			 		var count = data.data.total;
			 		var dataList = data.data.list;
			 		var txt = "";
			 		SysRoleListPage.userDataList = dataList;
			 		for(var i = 0 ; dataList != null && i < dataList.length ; i ++){
			 			txt +=SysRoleListPage.createRecordTxtUser(dataList[i], i);
			 		}
			 		
			 		SysRoleListPage.pagingToolerUser.showInPage(count, txt,"currentNumberPage");
			 	}		
			 });

	    },
	    
	    //创建表格中每一条记录的文本
	    createRecordTxtUser : function(data , index){
	    	
	    	var txt = "";
	    	
	    	var btnClass = data.bindRoleFlag ? "roleUnbindUserBtn" : "roleBindUserBtn";
	    	
			txt = '<tr>'+
						'<td><input type="checkbox" class="checkitem"  userId="'+data.id+'"/></td>'+
						'<td>'+CommonUtil.fillBlank(data.account)+'</td>'+
						'<td>'+CommonUtil.fillBlank(data.userName)+'</td>'+
						'<td>'+CommonUtil.fillBlank(data.gender)+'</td>'+
						'<td>'+CommonUtil.fillBlank(data.phoneNumber)+'</td>'+
						'<td style="color:'+(data.bindRoleFlag ? "green" : "orange")+'">'+(data.bindRoleFlag ? "已绑定" : "未绑定")+'</td>'+
						'<td>'+
							'<span class="permissionMenu '+btnClass+'" onclick="SysRoleListPage.bindUser('+index+')"  style="color:blue;cursor:pointer;">'+(data.bindRoleFlag ? "解绑" : "绑定")+'</span>&nbsp;'+
						'</td>'+
	    			  '</tr>';
			
	    	return txt;
	    },
	    
	    //绑定用户
	    bindUser : function(index){
	    	
	    	//当前编辑对象
	    	this.currentUserDetailRecord = this.userDataList[index];
	    	
	    	var currentUserDetailRecord = this.currentUserDetailRecord;
	    	
	    	var bindRoleFlag = currentUserDetailRecord.bindRoleFlag;
	    	
	    	var sysRoleId = this.currentUpdateRecord.id + "";
	    	var userIds = [];
	    	userIds.push(this.currentUserDetailRecord.id + "");
	    	var params = {"id" :  sysRoleId , "userIds" :  userIds};
	    	
	      	//若是已绑定 ,调解绑接口 , 否则, 调绑定接口
	    	var requestUrl = "/sysRole/" + (bindRoleFlag ? "roleUnbindUsers" : "roleBindUsers");
	  
	    	ajaxRequestByJSONParams(requestUrl , params , function(rst){
    			
	    		if(rst.code == 200){
		 			new $.zui.Messager(rst.message, {icon:'check' ,type: 'success',placement: 'center',time:'2000'}).show();
		 			SysRoleListPage.findUserList();
		 			return;
		 		}
		 		
		 		new $.zui.Messager(rst.message, {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
		 		
    		});
	    	
	    	
	    },
	    
	    //批量绑定
	    batchBindUser : function(type){
	    	
	    	var jqArr = $(".checkitem:checked");
	    	
	    	var tip = type == 1 ? "绑定" : "解绑";
	    	
	    	if(jqArr.length == 0){
	    		new $.zui.Messager("请勾选要"+tip+"的用户", {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
	    		return;
	    	}
	    	
	    	var userIds = [];
	    	
	    	for(var i = 0 ; i < jqArr.length ; i ++){
	    		userIds.push($(jqArr[i]).attr("userId"));
	    	}
	    	
	    	var sysRoleId = this.currentUpdateRecord.id + "";
	    	
	    	var params = {"id" :  sysRoleId , "userIds" :  userIds};
	    	
	      	//若是已绑定 ,调解绑接口 , 否则, 调绑定接口
	    	var requestUrl = "/sysRole/" + (type == 2 ? "roleUnbindUsers" : "roleBindUsers");
	    	
	    	ajaxRequestByJSONParams(requestUrl , params , function(rst){
    			
	    		if(rst.code == 200){
		 			new $.zui.Messager(rst.message, {icon:'check' ,type: 'success',placement: 'center',time:'2000'}).show();
		 			SysRoleListPage.findUserList();
		 			return;
		 		}
		 		
		 		new $.zui.Messager(rst.message, {icon:'times',type: 'danger',placement: 'center',time:'2000'}).show();
		 		
    		});
	    	
	    }
	    
}

$(function(){
	
	//初始化
	SysRoleListPage.init();
	
	//初始化表格
	SysRoleListPage.pagingTooler.initTableList();
	
});
